﻿// Copyright (C) 2009 - 2013 EvTech Project
//
// This program is free software: you can redistribute it and/or modify
// it under the +terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/. 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Printing;

namespace Piirto
{
    public partial class PaintForm : Form
    {
        private PiirtoMainForm piirtoMainForm;
        private SelectImageForm selectImageDlg;
        private List<DrawTool> drawHistory;

        public PaintForm()
        {
            InitializeComponent();
        }

        public PaintForm(PiirtoMainForm piirtoMainForm)
        {
            InitializeComponent();
            this.piirtoMainForm = piirtoMainForm;
            colorControl1.ColorSelected += colorControl_Click;
            this.selectImageDlg = new SelectImageForm("./images");
            this.paintImage.Image = selectImageDlg.getSelectedImage();
            this.currentColorImage.BackColor = this.colorControl1.getSelectedColor();
            drawHistory = new List<DrawTool>();
        }

        private void PaintForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
            this.piirtoMainForm.Show();
        }


        private void btnBack_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.piirtoMainForm.Show();
        }

        /**
         * Avaa kuvanvalintadialogi
         * 
         */
        private void btnLoad_Click(object sender, EventArgs e)
        {
            DialogResult dr = selectImageDlg.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                drawHistory.Clear();
                this.paintImage.Image = selectImageDlg.getSelectedImage();
            }
        }

        private void colorControl_Click(object sender, EventArgs e)
        {
            this.currentColorImage.BackColor = this.colorControl1.getSelectedColor();
        }

        private void PaintForm_Resize(object sender, EventArgs e)
        {
            int scaleX = this.Width / 100;
            int scaleY = this.Height / 100;
            paintImage.SetBounds(5 * scaleX, 5 * scaleY, 70 * scaleX, 75 * scaleY);
            controlPanel.SetBounds(80 * scaleX, 5 * scaleY, 15 * scaleX, 75 * scaleY);
            //colorPanel.SetBounds(5 * scaleX, 85 * scaleY, 90 * scaleX, 15 * scaleY);
        }

        private void paintImage_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            int x, y;

            if (paintImage.Image.Width / paintImage.Image.Height > paintImage.Width / paintImage.Height)
            {
                x = e.X * paintImage.Image.Width / paintImage.Width;
                y = (e.Y - (paintImage.Height - paintImage.Image.Height * paintImage.Width /
                    paintImage.Image.Width) / 2) * paintImage.Image.Width / paintImage.Width;
            }
            else
            {
                x = (e.X - (paintImage.Width - paintImage.Image.Width * paintImage.Height /
                    paintImage.Image.Height) / 2) * paintImage.Image.Height / paintImage.Height;
                y = e.Y * paintImage.Image.Height / paintImage.Height;
            }
            if(x >= 0 && y >= 0 && x < paintImage.Image.Width && y < paintImage.Image.Height)
            {
                FillTool tmpDraw = new FillTool(this.colorControl1.getSelectedColor(), paintImage.Image);
                if (tmpDraw.newPoint(x, y))
                {
                    Bitmap bm = new Bitmap(paintImage.Image);
                    Graphics g = Graphics.FromImage(bm);
                    tmpDraw.Paint(g, 0, 0, 1, 0);
                    g.Dispose();
                    drawHistory.Add(tmpDraw);
                    paintImage.Image = bm;
                }
            }
            this.Cursor = Cursors.Default;
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            TextInputDialog saveDialog = new TextInputDialog("Tallennetaan kuva", "Kirjoita nimesi", "Tallenna", "Peru");
            bool isSaved = false;
            while (!isSaved)
            {
                try
                {
                    string filename = "./saved/";
                    if (!Directory.Exists(filename))
                    {
                        Directory.CreateDirectory(filename);
                    }
                    saveDialog.ShowDialog();
                    if (saveDialog.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                    {
                        this.Cursor = Cursors.Default;
                        return;
                    }
                    filename += saveDialog.WrittenText;
                    filename += DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".bmp";
                    paintImage.Image.Save(filename);
                    isSaved = true;
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(ex.StackTrace);
                }
            }
            this.Cursor = Cursors.Default;
            InformationDialog.Show("Kuva on tallennettu");
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            ImagePrintDocument doc = new ImagePrintDocument(paintImage.Image);

            try
            {
                doc.Print();
                this.Activate();
                this.Cursor = Cursors.Default;
                InformationDialog.Show("Tulostetaan");
            }
            catch (Exception)
            {
                this.Cursor = Cursors.Default;
                InformationDialog.Show("Tulostus ei onnistu");
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            DialogResult dr = InformationDialog.Show("Haluatko varmasti tyhjentää?", MessageBoxButtons.YesNo);
            if (dr == System.Windows.Forms.DialogResult.Yes)
            {
                drawHistory.Clear();
                this.paintImage.Image = selectImageDlg.getSelectedImage();
            }
            this.Cursor = Cursors.Default;
        }

        private void btnUndo_Click(object sender, EventArgs e)
        {
            if (this.Cursor == Cursors.WaitCursor)
            {
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            if (drawHistory.Count > 0)
            {
                drawHistory.RemoveAt(drawHistory.Count - 1);
            }
            Bitmap bm = new Bitmap(selectImageDlg.getSelectedImage());
            Graphics g = Graphics.FromImage(bm);
            foreach (DrawTool dTool in drawHistory)
            {
                dTool.Paint(g, 0, 0, 1, 0);
            }
            g.Dispose();
            this.paintImage.Image = bm; 
            this.Cursor = Cursors.Default;
        }

        private void currentColorImage_Click(object sender, EventArgs e)
        {
            ColorDialog cd = new ColorDialog();
            cd.AnyColor = true;
            cd.AllowFullOpen = true;
            cd.SolidColorOnly = true;
            cd.FullOpen = true;
            if (cd.ShowDialog() == DialogResult.OK)
            {
                Color color = cd.Color;
                if (color.ToArgb() == FillTool.dontColor.ToArgb())
                {
                    if (color.B >=255)
                        color = Color.FromArgb(color.A, color.R, color.G, color.B-1);
                    else
                        color = Color.FromArgb(color.A, color.R, color.G, color.B + 1);
                }
                this.currentColorImage.BackColor = color;
                this.colorControl1.setSelectedColor(color);
            }
        }
    }
}
